<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Purchase extends CI_Controller {

	/** 采购管理
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct()
	 {
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->load->model('Purchase_m','m');
		$this->load->model('Product_m','pm');
		$this->pageSize =$this->config->item('pagenum');
		$this->proudctcate = array("1" => 'A类', "2" => 'B类', "3" => 'C类');
	 }
	
	/*****************
	**
	**  智能生成采购单
	**
	****************/
	function automaticProducePurchase()
	{
		$sl =  $this->input->get('sl');
		if($sl==2)
		{
			$where = " AND dailysales >0";
			$dailysales = "dailysales";
			$this->tpl->assign('sl',2);
		}elseif($sl==3)
		{
			$this->tpl->assign('sl',1);
		}else
		{
			$where = " AND onecangsales >0";
			$dailysales = "onecangsales";
			$this->tpl->assign('sl',1);
		}
		
		$where.=" AND g_sale_status !=4 and g_sale_status !=5 AND g_sale_status !=6";// 停产  清仓  暂停销售 不再显示
		//$where.=" and  length(goods_sku)!=8 AND (locate(11,goods_sku)!=1 or locate(12,goods_sku)!=1 ) and g_supplier=3 AND goods_id in (SELECT distinct goods_id FROM `db_goods_stock` WHERE `positions` !='' and positions !=0 )  ";

		
		$factory_id = $this->input->get('supplier');
        if($factory_id){
			$where.= " AND g_supplier = $factory_id ";
            $this->tpl->assign('supplier',$factory_id);
        }
		
		$isarea = $this->input->get('isarea');
        if($isarea){
			if($isarea==1)
			{
				$where.=" AND goods_id in (SELECT distinct goods_id FROM db_goods_attr WHERE  attr_value = '欧美' ) ";
			}
			if($isarea==2)
			{
				$where.=" AND goods_id in (SELECT distinct goods_id FROM db_goods_attr WHERE  attr_value = '亚洲'  ) ";
			}
			if($isarea==3)
			{
				$where.=" AND goods_id in (SELECT distinct goods_id FROM db_goods_attr WHERE   attr_value='通用' ) ";
			}
            $this->tpl->assign('isarea',$isarea);
        }

		$cate = $this->input->get('cate');
		if($cate)
		{
			$where.=" AND g_sale_cate = '".$cate."'";
			 $this->tpl->assign('cate',$cate);
		}
		$buyer = $this->input->get('buyer');
		if($buyer)
		{
			$where.="  and  ( locate(1100,goods_sku)!=1 and locate(1200,goods_sku)!=1 ) AND goods_id in (SELECT distinct goods_id FROM `db_goods` WHERE 1 and g_buyer ='".$buyer."'  ) ";
			 $this->tpl->assign('buyer',$buyer);
		}else{
			$where.=" and  ( locate(1100,goods_sku)!=1 and locate(1200,goods_sku)!=1 ) AND goods_id in (SELECT distinct goods_id FROM `db_goods_stock` WHERE 1 and (`positions` !='' AND  positions!='外购鞋子' AND  positions!='外购假发' AND  positions!='外购人偶' AND  positions NOT like '%DE%') ) ";
		}
		
		


		$filtertype = $this->input->get_post('filtertype')?$this->input->get_post('filtertype'):'productid';
		if ($filtertype) {
            $kw = trim($this->input->get_post('kw'));

			if($kw){
				if ($filtertype == 'productname') {
					$where .= " and goods_name like '%" . $kw . "%'";
				} elseif ($filtertype == 'productid') {
					$where .= " AND goods_sku like '%" . $kw . "%'";
				} elseif ($filtertype == 'positions') {
					 $where .= " and goods_id in(select distinct goods_id from `db_goods_stock` where `positions` like '%" . $kw . "%')";
				} else {
					$where .= " and  ($filtertype =   '" . $kw . "') ";
				}
				$this->tpl->assign("filtertype", $filtertype);
				$this->tpl->assign("kw", $kw);
			}
        }
		
		$g_procurement_DayNum = $this->input->get_post('g_procurement');//自己填写的采购天数
		if($g_procurement_DayNum)
		{
			 $this->tpl->assign("g_procurement", $g_procurement_DayNum);
		}else{

			 $this->tpl->assign("g_procurement", 15);
		}
		$alertnum_DayNum = $this->input->get_post('alertnum');//自己填写的警戒天数
		if($alertnum_DayNum)
		{
			 $this->tpl->assign("alertnum", $alertnum_DayNum);
		}else{

			 $this->tpl->assign("alertnum", 15);
		}

	
		$orderbysku =  $this->input->get('orderby');
		if($orderbysku)
		{
			if($orderbysku =='SDESC')
			{
				$ordersorder = " order by goods_sku ASC";
				$this->tpl->assign("orderbysku", 'SDESC');
			}else{
				$ordersorder = " order by $dailysales $orderbysku";
				$this->tpl->assign("orderbysku", $orderbysku);
			}
		}

		if($_COOKIE['ext_userid'])
		{
			$ext_userID = $_COOKIE['ext_userid'];
			$where.=" AND g_createID in ($ext_userID)";
			
		}else{
			if($_COOKIE['classid']==16)
			{
				//外部
				$userID = $_COOKIE['userid'];
				$where.= " AND g_supplier = 7 ";
			}
		}
		$list = $this->fun->getdatabaseslist("db_goods ", $where,"*",$ordersorder);
		//echo $this->db->last_query();
		//die;
		foreach($list as $key=>$rs)
		{
			//日销量乘以库存预警天数 = 库存预警数量
			//取库存数 
			$stock = $this->fun->getdatabasesdetail("db_goods_stock"," AND storage_id = 1 AND goods_id = ".$rs['goods_id']);
			
			if($g_procurement_DayNum)	//填写了使用填写的
			{
				$g_procurement = $g_procurement_DayNum;

			}else{

				if($rs['g_supplier'] ==3 )	//外采购
				{
					$g_procurement = $rs["g_procurement"]?$rs["g_procurement"]:7;	//采购天数默认7天
				}else{
					$g_procurement = $rs["g_procurement"]?$rs["g_procurement"]:30;	//采购天数默认60天
				}
			}

			
			if($rs["g_inventory_day"]>$alertnum_DayNum)
			{
				$alertnum = ceil(($rs[$dailysales]*$rs["g_inventory_day"]));
				$g_inventory_day = $rs["g_inventory_day"];
			}else{
				if($alertnum_DayNum)	//预警数
				{
					$alertnum = ceil(($rs[$dailysales]*$alertnum_DayNum));
					$g_inventory_day = $alertnum_DayNum;
				}else{
					$alertnum = $rs['alertnum'];
				}
			}

			if($stock['stock']<0)
			{
				$stock['stock'] = 0;
			}
			$sendgoodsnum = $this->pm->getsendthegoods($rs['goods_id'],1);	//待发货数
			//减去2号仓的库存
			$stockTwo = $this->fun->getdatabasesdetail("db_goods_stock"," AND storage_id = 2 AND goods_id = ".$rs['goods_id']);
			if($stockTwo['stock']<0)
			{
				$stockTwo['stock'] = 0;
			}

			$in_transit = $stock['in_transit']+$stockTwo['in_transit'];	//在途

			//获取海外仓申请的调拨数量
			$Needgoodsstock = $this->fun->getdatabasesdetail("t_overseapurchasing"," AND demandID in(SELECT DISTINCT id  FROM `t_oversea_demand` WHERE status = 3) and status = 0 and goodsno='".$rs["goods_sku"]."'","SUM(skunum) AS needskunum ,SUM(sendnums) AS needsendnums");
			$needskunum = $Needgoodsstock["needskunum"] - $Needgoodsstock["needsendnums"];

			$stockNums = $stock['stock'] + $stockTwo['stock'] - $sendgoodsnum - $needskunum;
			if($stockNums<$alertnum) //库存小于警戒库存
			{
				//需要采购的商品信息
			
				
				
			
			//15天的销量，减去库存，减去在途+待发货数-二号仓库存
			$nst = ceil(($rs[$dailysales]*$g_procurement)) - $stock['stock'] - $in_transit+$sendgoodsnum-$stockTwo['stock'];
			

			$neednst = $nst+$needskunum;
			
			//如果预警数小于当前库存，也直接需要采购 

			//预警库存不能少于78件  
			$needsum = $alertnum - $stock['stock'] - $stockTwo['stock'] - $in_transit + $sendgoodsnum ;
			//if($_COOKIE['userid']==295){
				//echo "商品".$rs['goods_sku']."->预警数".$alertnum."->在库数".$stock['stock']."->最低采购数".$neednst."需要的预警数->".$needsum;
				//echo "<br>";
			//}


			if($neednst>0 || $needsum >0){
				if($needsum <0) $needsum = 0;

				if($needsum>0)
				{
					if($needsum>$neednst)
					{
						$goodslist[$key]['memo'] = "预警采购数 = 日均销量($rs[$dailysales])*预警天数($g_inventory_day)+待发($sendgoodsnum)+海外调拨($needskunum)-库存($stock[stock]+$stockTwo[stock])-在途($in_transit) ";
					}else{
						$goodslist[$key]['memo'] = "销量采购数=日均销量($rs[$dailysales])*采购天数($g_procurement)+待发($sendgoodsnum)-库存($stock[stock]+$stockTwo[stock])-在途($in_transit)+海外调拨($needskunum)";
					}
				}else{
					$goodslist[$key]['memo'] = "销量采购数=日均销量($rs[$dailysales])*采购天数($g_procurement)+待发($sendgoodsnum)-库存($stock[stock]+$stockTwo[stock])-在途($in_transit)+海外调拨($needskunum)";
				}
				$goodslist[$key]['goods_sku'] = $rs['goods_sku'];
				$goodslist[$key]['goods_id'] = $rs['goods_id'];
				$goodslist[$key]['g_supplier'] = $rs['g_supplier'];
				$goodslist[$key]['goods_parentID'] = $rs['goods_parentID'];
				$goodslist[$key]['goods_parent_sku'] = $rs['goods_parent_sku'];
				$goodslist[$key]['goods_name'] = $rs['goods_name'];
				$goodslist[$key]['g_costprice'] = $rs['g_costprice'];
				$goodslist[$key]['g_procurement'] = $g_procurement;	//采购天数
				$goodslist[$key]['g_inventory_day'] = $g_inventory_day;//库存警戒天数
				$goodslist[$key]['alertnum'] = $alertnum;
				$stocknums =  $stock['stock']+$stockTwo['stock'];
				$goodslist[$key]['stock'] = $stocknums?$stocknums:0;
				if($needsum>$neednst)
				{
					$goodslist[$key]['neednst'] = $needsum+ $needskunum;//如果预警数大于
				}else{
					$goodslist[$key]['neednst'] = $neednst;//实际要采购数
				}
				
				if($needsum>$nst)
				{
					$goodslist[$key]['nst'] = $needsum;
				}else{
					$goodslist[$key]['nst'] = $nst;
				}
				$goodslist[$key]['needskunum'] = $needskunum?$needskunum:0;
				$goodslist[$key]['positions'] = $stock['positions'];
				$goodslist[$key]['in_transit'] = $in_transit;
				if($stock['waitday']>0)
				{
					$goodslist[$key]['waitday'] = date("Y-m-d",$stock['waitday']);
				}else{
					$goodslist[$key]['waitday'] = 0;
				}
				$goodslist[$key]['sales1'] = $rs['sales1']+$rs['fbasale1'];
				$goodslist[$key]['sales2'] = $rs['sales2']+$rs['fbasale2'];
				$goodslist[$key]['sales3'] = $rs['sales3']+$rs['fbasale3'];
					$goodslist[$key]['dailysales'] = $rs[$dailysales];
				$goodslist[$key]['saleNum'] = $rs['saleNum'];
				$goodslist[$key]['g_sale_status'] = $rs['g_sale_status'];
					
					$goodslist[$key]["sendgoodsnum"] = $sendgoodsnum;
			}
			}
		}

		//需要读取同父类下的SKU是否需要采购16261-F(12001261)-M
		$this->tpl->assign("goodslist", $goodslist);
		$this->tpl->assign("factory", $this->db->get('db_factory')->result_array());
		$this->tpl->assign("proudctcate", $this->proudctcate);
		
		$userlist = $this->fun->getdatabaseslist('db_goods'," AND g_buyer is NOT NULL",'DISTINCT(g_buyer)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['g_buyer'];
		}
        $this->tpl->assign("userlist", $yuanl);
		$str_warehouse = $this->config->item('temporary_warehouse');
        $arr_warehouse = explode("\n",$str_warehouse);
        $arr_positions = array();//具体仓库位置
        foreach($arr_warehouse as $k=>$v){
            $arr_value = explode("|",trim($v));
            $arr_positions[$k]=$arr_value[1];
        }
		if($arr_positions)
		{
			$arr_positions  =implode("｜",$arr_positions);
			$this->tpl->assign("arr_positions", $arr_positions);
		}
		
        $this->tpl->display("purchase/automaticProducePurchase.tpl");
	}
	//生成工厂采购单
	public function addFactoryOrder(){
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "")
			$nowpage = 1;
		$where = "";
		$factory_id = $this->input->get('supplier');
		if($factory_id){
			$where.= " AND g_supplier = $factory_id ";
			$this->tpl->assign('supplier',$factory_id);
		}
		//采购天数
		if(trim($this->input->get('buy_days'))){
			$buy_days = trim($this->input->get('buy_days'));
			$this->tpl->assign("buy_days", $buy_days);
		}else{
			$buy_days = 60; //默认60天
			$this->tpl->assign("buy_days", $buy_days);
		}
		//采购人员
		$buyer = $this->input->get('buyer');
		if($buyer)
		{
			$where.=" AND goods_id in (SELECT distinct goods_id FROM `db_goods` WHERE 1 and g_buyer ='".$buyer."'  ) ";
			$this->tpl->assign('buyer',$buyer);
		}
		$filtertype = $this->input->get_post('filtertype')?$this->input->get_post('filtertype'):'productid';
		if ($filtertype) {
			$kw = trim($this->input->get_post('kw'));

			if($kw){
				if ($filtertype == 'productname') {
					$where .= " and goods_name like '%" . $kw . "%'";
				} elseif ($filtertype == 'productid') {
					$where .= " AND (goods_sku like '%" . $kw . "%' or goods_parent_sku like '%".$kw."%')";
				} elseif ($filtertype == 'positions') {
					$where .= " and goods_id in(select distinct goods_id from `db_goods_stock` where `positions` like '%" . $kw . "%')";
				} else {
					$where .= " and  ($filtertype =   '" . $kw . "') ";
				}
				$this->tpl->assign("filtertype", $filtertype);
				$this->tpl->assign("kw", $kw);
			}
		}
		//商品sku进行排序
		$orderbyxuhao =  $this->input->get('orderbyxuhao');
		if($orderbyxuhao)
		{
			$orderby =" order by goods_sku {$orderbyxuhao}";
			if($orderbyxuhao=='ASC')
			{
				$this->tpl->assign("orderbyxuhao",'DESC');
			}else{
				$this->tpl->assign("orderbyxuhao",'ASC');
			}

		}else{
			$orderby =" order by goods_sku DESC";
			//$this->tpl->assign("orderbyxuhao",'DESC');
		}

		//根据商品销量进行排序
		$flag = 0;
		$orderbystock =  $this->input->get('orderbystock');
		if($orderbystock)
		{
			if($orderbystock=='ASC')
			{
				$flag = 1; //升序
				$this->tpl->assign("orderbystock",'ASC');
			}else{
				$flag = 2; //降序
				$this->tpl->assign("orderbystock",'DESC');

			}
		}else{
			$flag = 2;
			$this->tpl->assign("orderbystock",'DESC');
		}
		//获取版型
		$versiontype = trim($this->input->get("versiontype"));
		if($versiontype){
			$this->tpl->assign("versiontype",$versiontype);
			if($versiontype==1){
				$version = "亚洲";
			}
			if($versiontype==2){
				$version = "欧美";
			}
		}
		//30日内销量  订单列表
		$cur_timestamp = time();

		//一定时间内销量
		$buy_date = trim($this->input->get("buy_date"));
		$sl =  $this->input->get('sl');
		if($buy_date){
			$this->tpl->assign('buy_date',$buy_date);
			$date_day = date("Y-m-d H:i:s",$cur_timestamp-$buy_date*86400);
			if($sl){
				$this->tpl->assign('sl',$sl);
			}else{
				$sl = 0;
				$this->tpl->assign('sl',$sl);
			}
		}else{
			$sl = 0;
			$this->tpl->assign('sl',$sl);
			$this->tpl->assign('buy_date',90); //默认三个月
			$buy_date = 90;
			$date_day = date("Y-m-d H:i:s",$cur_timestamp-90*86400);
		}
		// 根据筛选条件来计算
		$cur_date = date("Y-m-d H:i:s",$cur_timestamp); //当前日期
		if($buy_date==30){
			$this->tpl->assign('buy_title',"30天");
		}
		if($buy_date==90){
			$this->tpl->assign('buy_title',"90天");
		}
		if($buy_date==180){
			$this->tpl->assign('buy_title',"半年");
		}
		if($buy_date==365){
			$this->tpl->assign('buy_title',"一年");
		}



		$cur_month_start = date("Y-m-01");
		$cur_month_end   = $cur_date; //当月日期

		//$last_year_timestamp = $cur_timestamp-(365+180)*86400;

		$year = date("Y");
		$last_year = $year-1;
		$last_year_begin = $last_year."-08-01";
		$last_year_end = $last_year."-10-31 23:59:59";
		//AND a.goods_sn in({$goods_sku})
		if($versiontype){
			$sql_num = "SELECT a.goods_id FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id ".
				" LEFT JOIN db_goods_attr c ON a.goods_id = c.goods_id  ".
				"WHERE b.dates >= '{$date_day}' AND b.order_status in(4,5)  AND ".
				" c.attr_value = '{$version}' AND ".
				"b.order_source in('正常订单','手工创建','拆分订单','合并订单') GROUP BY a.goods_id HAVING sum(a.goods_number) >".$sl;
		}else{
			$sql_num = "SELECT a.goods_id FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id ".
				"WHERE b.dates >= '{$date_day}' AND b.order_status in(4,5)  AND ".
				"b.order_source in('正常订单','手工创建','拆分订单','合并订单') GROUP BY a.goods_id HAVING sum(a.goods_number) >".$sl;
		}

		$where.=  " and goods_id in({$sql_num}) ";
		$where.=" AND g_sale_status !=4 and g_sale_status !=5 AND g_sale_status !=6";// 停产  清仓  暂停销售 不再显示
		$where.=" and  length(goods_parent_sku)=8 AND (locate(1100,goods_parent_sku)=1 or locate(1200,goods_parent_sku)=1 ) AND locate(1200,goods_sku)!=1 AND locate(1100,goods_sku)!=1  ";
		//$orderby = " order by goods_sku DESC";
		$this->pageSize = 20;
		$fields = "goods_id,goods_sku,goods_parent_sku,g_costprice,goods_name,g_updatetime";
		//$list = $this->fun->getalllist('db_goods', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields);


		$list['list'] = $this->fun->getdatabaseslist('db_goods',$where,$fields,$orderby);
		$goodslist = array();
		foreach($list['list'] as $key=>$rs)
		{
			//筛选日期内销量
			$halfyear_num = $this->fun->goods_history_sales($rs['goods_sku'],$date_day,$cur_date);
			//当月销量
			$curmonth_num = $this->fun->goods_history_sales($rs['goods_sku'],$cur_month_start,$cur_month_end);
			//去年旺季销量
			$lastyear_num = 0;
			$lastyear_num = $this->fun->goods_history_sales($rs['goods_sku'],$last_year_begin,$last_year_end);

			$list['list'][$key]['hotdailysales'] = round($lastyear_num/90,2);

			$list['list'][$key]['halfyear_num'] = $halfyear_num;
			$list['list'][$key]['curmonth_num'] = $curmonth_num;
			$list['list'][$key]['lastyear_num'] = $lastyear_num;

			//取库存数
			$stock = $this->fun->getdatabasesdetail("db_goods_stock"," AND storage_id in(1,2) AND goods_id = ".$rs['goods_id']," sum(stock) as stock,sum(in_transit) as in_transit,group_concat(positions) as positions ");
			$list['list'][$key]['positions'] = $stock['positions'];
			$list['list'][$key]['stock'] = $stock['stock'];
			$list['list'][$key]['in_transit'] = $stock['in_transit'];


			//总待发货
			$waitgoods = 0;
			$ress = $this->fun->getdatabasesdetail('db_order_sell a left join db_order_list b on a.order_id = b.order_id '," AND  a.`goods_id` = '{$rs['goods_id']}' AND b.order_status in (2,3) AND  b.shipping_status = 4 "," sum(a.goods_number) as goods_number");
			if($ress){
				$waitgoods = $waitgoods+$ress['goods_number'];
			}
			$list['list'][$key]['waitgoods'] = $waitgoods; //待发货数量



			//采购数量计算
			//$buy_num = $halfyear_num*0.8 + $lastyear_num*0.2 + ($halfyear_num*0.8 + $lastyear_num*0.2)*0.1 - $stock['in_transit'] - $stock['stock'] + $waitgoods;
			//$buy_num = floor($buy_num);
			//日销量 近似约值 淡季日均销量
			$list['list'][$key]['dailysales'] = round($halfyear_num/$buy_date,2);

			$buy_num = $buy_days*$list['list'][$key]['dailysales'];
			$buynum = ceil($buy_num)-$stock['in_transit']-$stock['stock']+$waitgoods;
				$list['list'][$key]['buy_num'] = ceil($buy_num)-$stock['in_transit']-$stock['stock']+$waitgoods;

			//$list['list'][$key]['calcval'] = $halfyear_num.",".$lastyear_num.",".$stock['in_transit'].",".$stock['stock'].",".$waitgoods;

			$list['list'][$key]['g_updatetime'] = date("Y-m-d",strtotime($rs['g_updatetime']));

			//需要显示数据
			if($buynum>0){
				$goodslist['list'][$key]['hotdailysales'] = round($lastyear_num/90,2);
				$goodslist['list'][$key]['dailysales'] = round($halfyear_num/$buy_date,2);
				$goodslist['list'][$key]['halfyear_num'] = $halfyear_num;
				$goodslist['list'][$key]['curmonth_num'] = $curmonth_num;
				$goodslist['list'][$key]['lastyear_num'] = $lastyear_num;
				$goodslist['list'][$key]['positions'] = $stock['positions'];
				$goodslist['list'][$key]['stock'] = $stock['stock'];
				$goodslist['list'][$key]['in_transit'] = $stock['in_transit'];
				$goodslist['list'][$key]['waitgoods'] = $waitgoods;
				$goodslist['list'][$key]['buy_num'] = ceil($buy_num)-$stock['in_transit']-$stock['stock']+$waitgoods;
				$goodslist['list'][$key]['g_updatetime'] = date("Y-m-d",strtotime($rs['g_updatetime']));
				$goodslist['list'][$key]['goods_id'] = $rs['goods_id'];
				$goodslist['list'][$key]['goods_sku'] = $rs['goods_sku'];
				$goodslist['list'][$key]['goods_parent_sku'] = $rs['goods_parent_sku'];
				$goodslist['list'][$key]['g_costprice'] = $rs['g_costprice'];
				$goodslist['list'][$key]['goods_name'] = $rs['goods_name'];
			}
		}
		//按照商品销量进行排序
		if($flag){
			$arr_goods_sort = array();
			if($goodslist['list']){
				foreach($goodslist['list'] as $k=>$v){
					$arr_goods_sort[$k] = $v['halfyear_num'];
				}
				if($flag==1){
					array_multisort($arr_goods_sort,SORT_ASC,$goodslist['list']); //升序排序
				}
				if($flag==2){
					array_multisort($arr_goods_sort,SORT_DESC,$goodslist['list']); //降序排序

				}
			}

		}

		$this->tpl->assign("total", count($goodslist['list']));
		//$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		//$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		//$this->tpl->assign("total", $list["total"]);
		//$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("goodslist", $goodslist["list"]);
		//$this->tpl->assign("goodslist", $list["list"]);
		$this->tpl->assign("factory", $this->db->get('db_factory')->result_array());

		$userlist = $this->fun->getdatabaseslist('db_goods'," AND g_buyer is NOT NULL",'DISTINCT(g_buyer)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['g_buyer'];
		}
		$this->tpl->assign("userlist", $yuanl);

		$this->tpl->display("purchase/addfactoryorder.tpl");
	}
	/**手动盘点库存日志**********/
	function inputstock()
	{
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = " ";
		
		
		
		
		
		if($this->input->get_post('cang'))
		{
			$cang = intval($this->input->get_post('cang'));
			 $where.=" AND tostock ='".$cang."'";
			 $this->tpl->assign("cang", intval($this->input->get_post('cang')));
		}


		$starttime = trim($this->input->get('starttime'));
		if ($starttime) {
			$times = $starttime . " 00:00:00";
			$timess = strtotime($times);
			$where .= " AND (intime >= '" . $timess . "')";
			$this->tpl->assign("starttime", $starttime);
		}

		$endtime = trim($this->input->get('endtime'));
		if ($endtime) {
			$times = $endtime . " 23:59:59";
			$endtimes = strtotime($times);
			$where .= " AND (intime <= '" . $endtimes. "')";
			$this->tpl->assign("endtime", $endtime);
		}
		if ($this->input->get_post('kw')) {
			$kw = $this->input->get_post('kw');
			$where .= " AND goods_sku like '%" . $kw. "%'";
			$this->tpl->assign("kw", $kw);
		}

		$list = $this->fun->getalllist("db_goods_inventory ", $where, $nowpage, $if_csv, $this->pageSize, $orderby);
		foreach($list["list"] as $key=>$rs)
		{
			 $list["list"][$key]['waittime'] =date("Y-m-d H:i:s",$rs['intime']);

		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlist", $list["list"]);


		$storage = $this->db->get_where("db_storage"," isdel = 0")->result_array();
		$this->tpl->assign("storagelist", $storage);
		
		$this->tpl->assign("warehouses",$this->db->get_where("db_storage",array("isdel"=>0))->result_array());//货运方式
		$this->tpl->display("purchase/handinputstock.tpl");
	}
	function handinputstock()
	{
		if($_COOKIE["classid"]==3)
		{
			$where=" AND id >2";
		}
		$storage = $this->db->get_where("db_storage"," isdel = 0 $where")->result_array();
		$this->tpl->assign("storagelist", $storage);
		$this->tpl->display("purchase/handinputstockmode.tpl");
	}
	/****************
	** 手动入库操作
	*************/
	function handstorage()
	{
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = " ";
		if($this->input->get_post('status'))
		{
			$status = intval($this->input->get_post('status'));
			if($ks==2) $where.=" AND status =0";
			if($ks==3) $where.=" AND status =1";


			$this->tpl->assign("status", intval($this->input->get_post('status')));
		}
		 
		
		if($this->input->get_post('ks'))
		{
			$ks = intval($this->input->get_post('ks'));
			if($ks==2) $where.=" AND istype =2";
			if($ks==3) $where.=" AND istype =1";
			if($ks==4) $where.=" AND istype =3";
			if($ks==5) $where.=" AND istype =5";
			 $this->tpl->assign("ks", intval($this->input->get_post('ks')));
		}
		
		
		if($this->input->get_post('cang'))
		{
			$cang = intval($this->input->get_post('cang'));
			 $where.=" AND tostock ='".$cang."'";
			 $this->tpl->assign("cang", intval($this->input->get_post('cang')));
		}


		$starttime = trim($this->input->get('starttime'));
		if ($starttime) {
			$times = $starttime . " 00:00:00";
			$timess = strtotime($times);
			$where .= " AND (intime >= '" . $timess . "')";
			$this->tpl->assign("starttime", $starttime);
		}

		$endtime = trim($this->input->get('endtime'));
		if ($endtime) {
			$times = $endtime . " 23:59:59";
			$endtimes = strtotime($times);
			$where .= " AND (intime <= '" . $endtimes. "')";
			$this->tpl->assign("endtime", $endtime);
		}
		if ($this->input->get_post('kw')) {
			$kw = $this->input->get_post('kw');
			$where .= " AND (goods_sku like '%" . $kw. "%' or  memo like '%" . $kw. "%')";
			$this->tpl->assign("kw", $kw);
		}

		$list = $this->fun->getalllist("db_goods_handstorage ", $where, $nowpage, $if_csv, $this->pageSize, $orderby);
		foreach($list["list"] as $key=>$rs)
		{
			 $list["list"][$key]['waittime'] =date("Y-m-d H:i:s",$rs['intime']);

		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlist", $list["list"]);
		
		if($_COOKIE["classid"]==3)
		{
			$wheresql=" AND id >2";
		}

		$storage = $this->db->get_where("db_storage"," isdel = 0 $wheresql")->result_array();
		$this->tpl->assign("storagelist", $storage);
		
		$this->tpl->assign("warehouses",$this->db->get_where("db_storage",array("isdel"=>0))->result_array());//货运方式
		$this->tpl->display("purchase/handstorage.tpl");
	}
	function savehandstorage()
	{
		
		$istype =  $this->input->post('istype');
		if($istype==1)
		{
			$goodslist = trim($this->input->post('goodslist'));
			$tostock   = $this->input->post('tostock');
		}else{
			$goodslist = trim($this->input->post('togoodslist'));
			$tostock   = $this->input->post('istostock');
		}
		if(!$goodslist)
		{
			die('没有提交数据!');
		}

		$strgoodslist = explode("\n",$goodslist);
		foreach($strgoodslist as $key=>$rs)
		{
			 $rs = str_replace("，", ",", $rs); //替换英文逗号,
			 $goods = explode(",",$rs);
			
			$post="";
			$detail = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".$goods[0]."'");
			if($detail)
			{
				$detailstock = $this->fun->getdatabasesdetail('db_goods_stock'," AND goods_id='".$detail["goods_id"]."' AND storage_id = '".$tostock."' ");
				$detailimg= $this->fun->getdatabasesdetail('db_goods_images'," AND goods_id='".$detail["goods_id"]."'");
				$oldnum = $detailstock['stock']?$detailstock['stock']:0;
				$post["goods_id"] = $detail['goods_id'];
				$post["goods_name"] = $detail['goods_name'];
				if($istype==1)
				{
					$post["oldnum"] = $oldnum;
					$post["newnum"] = $oldnum+$goods[1];	//入库
				}else{
					$post["oldnum"] = $oldnum;
					$post["newnum"] = $oldnum-$goods[1];	//出库
				}
				$post["images"] = $detailimg['thumb_url']?$detailimg['thumb_url']:"/fuman/images/s-l500.jpg";
				
			}else{
				
				$post["goods_id"] = 0;
				$post["goods_name"] = '没有找到这个SKU';
				$post["oldnum"] = 0;
				$post["newnum"] = 0;
				$post["images"] = '/fuman/images/s-l500.jpg';
			}
			
			$post["goods_sku"] = $goods[0];
			$post["goods_instock"] = $goods[1]?$goods[1]:0;
			$post["istype"] = $istype;
			$post["tostock"] = $tostock;
			$post["status"] = 0;	//待处理
			$post["intime"] = time();
			$post["oper"] = $_COOKIE["userid"];
			$post["opername"] =  $_COOKIE["username"];
			$rsdbstock = $this->fun->getdatabasesdetail('db_storage'," AND id='".$tostock."'");
			$post["storagename"] =  $rsdbstock["storagename"];

			$this->db->insert("db_goods_handstorage",$post);
		}
		
		header("location:/purchase/handstorage?status=0");
		
	}
	/**************
	** 手动出库
	*******************/
	function findoutbound()
	{
		$this->tpl->display("purchase/instorage.tpl");
	}

	/***********************
	*** 添加采购单
	***********************/
	function addpurchase()
	{
		
		/**********从库存预警提交的信息*********/
		$goods_id_list   = $this->input->post('goods_id_list');	//需要采购的ID
		$goods_nums_list = $this->input->post('goods_nums_list');//需要采购的数量
		
		if($goods_id_list && $goods_nums_list)
		{
			$detail_list = $this->m->getProducePurchase($goods_id_list,$goods_nums_list);
			$this->tpl->assign("detail_list",$detail_list);
			
		}
		/**********从库存预警提交的信息*********/
		

		$storagelist = $this->db->get_where('db_storage', 'isdel=0')->result_array();
        $factorys=$this->db->get('db_factory')->result_array();
        $this->tpl->assign("factorylist", $factorys);
        $this->tpl->assign("storagelist", $storagelist);
		$this->tpl->assign("randmon", time());
		$this->tpl->display("purchase/addpurchase.tpl");
	}

	
	function savepurchase()
	{
		$id=$this->m->save();
		header("location:/purchase/purchaselist?id={$id}");
	}
	function ordermod()
	{
		$t = $this->input->get('t');
		$id = $this->input->get('id');
		 if($id > 0)
	     {
			$detail = $this->m->getBuyListByUid($id);
	        $this->tpl->assign("detail",$detail);
			$detail_list = $this->m->getBuyListvice($detail['id']);
			$this->tpl->assign("detail_list",$detail_list);
			 $sql = "SELECT GROUP_CONCAT(id) as strs_id,sum(nums) as nums FROM db_purchase_vice WHERE pid = '{$detail['id']}' ";
			 $rs = $this->db->query($sql)->row_array();

		     $this->tpl->assign("totalnums",$rs['nums']);
			 //入库日志信息
			 $loglist = $this->db->get_where('db_purchase_vicelog',  "pid in ({$rs['strs_id']}) ")->result_array();
			 $this->tpl->assign("loglist", $loglist);

			 //状态日志信息
			 $statusloglist = $this->db->order_by("id","desc")->get_where('db_externalbuy_log',  "purchase_id = {$id} ")->result_array();
			 $this->tpl->assign("statusloglist", $statusloglist);
			
	     }
         
	    $this->tpl->assign("uid",$id);
		$storagelist = $this->db->get_where('db_storage', 'isdel=0')->result_array();
        $factorylist=$this->db->get('db_factory')->result_array();
        $factory=array_column($factorylist,'name','id');
        $made_status=array("待生产","开始生产","生产完成","已发运");
        $this->tpl->assign('made_status',$made_status);
        $this->tpl->assign('factory',$factory);
        $this->tpl->assign('factorylist',$factorylist);
        $this->tpl->assign("storagelist", $storagelist);
        //dump($storagelist);
		if($t=='show'){
			$this -> tpl -> display("purchase/addpurchaseshow.tpl");
		}
		else
			$this -> tpl -> display("purchase/addpurchase.tpl");	    
	}
	
	/***********
	*** 扫描入库
	***********/
	function instorage()
	{
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = " AND status =2 and chkflag = 1";
		if($this->input->get_post('id'))
		{
		   $where.=" AND id = ".intval($this->input->get_post('id'));
		}
		$list = $this->fun->getalllist("db_purchase_list ", $where, $nowpage, $if_csv, $this->pageSize, $orderby);
		foreach($list["list"] as $key=>$rs)
		{
			 $waittime = strtotime($rs['opertime']) + 86400*$rs['daysum'];
			 $list["list"][$key]['waittime'] =date("Y-m-d H:i:s",$waittime);

		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlist", $list["list"]);

	
	
        $this->tpl->display("purchase/instorage.tpl");
	}
	/*****
		扫单入库
	*******/
	function instock($id)
	{
		$detail = $this->m->getBuyListByUid($id," AND chkflag = 1 AND status = 2");
		$this->tpl->assign("detail",$detail);
		//获取采购单信息
		$detail_list = $this->m->getBuyListvice($detail['id']);
		$this->tpl->assign("detail_list",$detail_list);
		
	    $this -> tpl -> display("purchase/instock.tpl");	 
	}

	/*********
	***	质检流程
	***
	******************/
	function qualityinspection()
	{
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = " AND status =2";
		if($this->input->get_post('id'))
		{
		   $where.=" AND id = ".intval($this->input->get_post('id'));
		}

		$starttime = trim($this->input->get_post('starttime'));
		if($starttime)
		{
			 $where.=" AND opertime >='".$starttime." 00:00:00"."'";
			 $this->tpl->assign("starttime", $starttime);
		}
		$endtime = trim($this->input->get_post('endtime'));
		if($endtime)
		{
			 $where.=" AND opertime <='".$endtime." 23:59:59'";
			 $this->tpl->assign("endtime", $endtime);
		}
		$kw = trim($this->input->get_post('kw'));
		if($kw)
		{
			 $where.=" AND (tb_ordersn like '%".$kw."%' or tb_kd like '%".$kw."%')";
			 $this->tpl->assign("kw", $kw);
		}
		$status = trim($this->input->get_post('status'));
		if($status){
			$where.=" AND chkflag = '{$status}' ";
			$this->tpl->assign("status", $status);
		}else{
			$where.=" AND chkflag = 0 ";
		}
		$supplier = trim($this->input->get_post('supplier'));
		if($supplier){
			$where.=" AND made_factory = '{$supplier}' ";
			$this->tpl->assign("supplier", $supplier);
		}

		$kws = trim($this->input->get_post('kws'));
		if($kws)
		{
			 $where.=" AND orderstockid like '%".$kws."%'";
			 $this->tpl->assign("kws", $kws);
		}
		$buyer = trim($this->input->get_post('buyer'));
		if($buyer){
			$where.=" AND createuser like '%".$buyer."%'";
			$this->tpl->assign("buyer", $buyer);
		}else{
			if($_COOKIE['department'] == 1 || $_COOKIE['classid']==10 || $_COOKIE['department']==18){ //超级管理员 1 仓管部门10
			}else{
				$where.=" AND createuser = '".$_COOKIE['username']."'";
			}

		}

		if($_COOKIE['ext_userid'])
		{
			$ext_userID = $_COOKIE['ext_userid'];
			$where.=" AND oper in ($ext_userID)";
			
		}

		$buyerlist = $this->fun->getdatabaseslist('db_purchase_list'," AND createuser is NOT NULL ",'DISTINCT(createuser)');
		foreach($buyerlist as $key=>$rs)
		{
			$buyers[] = $rs['createuser'];
			$this->tpl->assign("buyerlist", $buyers);
		}

		$goodssku = trim($this->input->get_post('goodssku'));
		if($goodssku)
		{
			 $where.=" AND id in (SELECT pid FROM db_purchase_vice WHERE good_no like '%".$goodssku."%')";
			 $this->tpl->assign("goodssku", $goodssku);
		}
		$skucode = trim($this->input->get_post('skucode'));
		if($skucode)
		{
			 $skumemocode = "->".$skucode;
			 $where.=" AND id in (SELECT pid FROM db_purchase_vice WHERE skucode like '%".$skucode."%' or skumemo like '%".$skumemocode."%')";
			 $this->tpl->assign("skucode", $skucode);
		}

		$factorys = $this->fun->getdatabaseslist("db_factory");
		$this->tpl->assign("factorys",$factorys);


		$list = $this->fun->getalllist("db_purchase_list ", $where, $nowpage, $if_csv, $this->pageSize, $orderby);
		//echo $this->db->last_query();
		foreach($list["list"] as $key=>$rs)
		{
			 $waittime = strtotime($rs['opertime']) + 86400*$rs['daysum'];
			 $list["list"][$key]['waittime'] =date("Y-m-d H:i:s",$waittime);

			$sql = "SELECT GROUP_CONCAT(good_no) as goods_no,GROUP_CONCAT(nums) as nums,GROUP_CONCAT(id) as id FROM db_purchase_vice WHERE pid = '{$rs['id']}' ";
			$res = $this->db->query($sql)->row_array();
			$arr_goods_no = explode(",",$res['goods_no']);
			$arr_nums = explode(",",$res['nums']);
			$arr_id = explode(",",$res['id']);
			$arr_new_goods_no = array();
			foreach($arr_goods_no as $k=>$v){
				$s_log = "SELECT sum(inStockNum) as inStockNum FROM db_purchase_vicelog WHERE good_no ='{$v}' AND pid = '{$arr_id[$k]}' GROUP BY pid ";
				$r_log = $this->db->query($s_log)->row_array();
				if($r_log['inStockNum']<$arr_nums[$k]){
					$arr_new_goods_no[$k] = "<span style='color:red;' title='红色标记sku表示采购数大于入库数'>".$v."</span>";
				}else{
					$arr_new_goods_no[$k] = $v;
				}

			}
			$res['goods_no'] = implode(",",$arr_new_goods_no);
			$list["list"][$key]['goods_no'] = str_replace(",","<br/>",$res['goods_no']);

		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlist", $list["list"]);

        $this->tpl->display("purchase/qualityinspection.tpl");
	}
	/**********
	*** 质检操作
	*************/
	function check_goods($id)
	{
		//取原始的采购单数据
	    $detail = $this->m->getBuyListByUid($id);
		$this->tpl->assign("detail",$detail);
		//获取采购单信息
		$detail_list = $this->m->getBuyListvice($detail['id']);
		foreach($detail_list as $k=>$v){
			$sql = "SELECT * FROM db_purchase_vicelog WHERE pid = {$v['id']} ";
			$rs  = $this->db->query($sql)->result_array();
			$detail_list[$k]['log'] =$rs;
		}
		$rs = $this->db->query("SELECT * FROM db_purchase_list WHERE id = '{$detail_list[0]['pid']}' ")->row_array();
		$batchorder = $this->db->query("SELECT * FROM db_batchorder WHERE order_id = '{$rs['tb_ordersn']}' ")->row_array();
		if($batchorder){
			$this->tpl->assign("end_flag",$batchorder['end_flag']);
		}
		
		//日志信息
		$sql = "SELECT GROUP_CONCAT(id) as strs_id FROM db_purchase_vice WHERE pid = '{$detail_list[0]['pid']}' ";
		$rs = $this->db->query($sql)->row_array();

		$loglist = $this->db->get_where('db_purchase_vicelog',  "pid in ({$rs['strs_id']}) ")->result_array();
		$this->tpl->assign("loglist", $loglist);
		

		$this->tpl->assign("detail_list",$detail_list);
		$this->tpl->assign("valuedate",date("Y-m-d"));

	    $this -> tpl -> display("purchase/check_good.tpl");	 
	}
	function purchaselist()
	{
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
		$status = $this->input->get_post('status');
		if($status)
		{
			if($status==1)
			{
				$where = " AND status = 1";
			}
			if($status==2)
			{
				$where = " AND status = 2 AND chkflag = 0";
			}
			if($status==3)
			{
				$where = " AND chkflag = 1";
			}
			$this->tpl->assign("status", $status);
		}else{
			if(trim($this->input->get_post('kw')) ||  trim($this->input->get_post('goodssku')) ||  trim($this->input->get_post('id')) ||  trim($this->input->get_post('ps')))
			{
			}else{
				$where = " AND status = 1";
			}

		}

        
		if($this->input->get_post('id'))
		{
		  // $where.=" AND id = ".intval($this->input->get_post('id'));
		   $id = trim($this->input->get_post('id'));
		   $where.=" AND id in($id)";
		}
		if($this->input->get_post('ispay'))
		{
		   $ispay = $this->input->get_post('ispay');
		   $where.=" AND ps = ".intval($ispay);
		   $this->tpl->assign("ispay", $ispay);
		}

		$starttime = trim($this->input->get_post('starttime'));
		if($starttime)
		{
			 $where.=" AND opertime >='".$starttime." 00:00:00"."'";
			 $this->tpl->assign("starttime", $starttime);
		}
		$endtime = trim($this->input->get_post('endtime'));
		if($endtime)
		{
			 $where.=" AND opertime <='".$endtime." 23:59:59'";
			 $this->tpl->assign("endtime", $endtime);
		}
		$kw = trim($this->input->get_post('kw'));
		$tys = trim($this->input->get_post('tys'));
		$this->tpl->assign("tys", $tys);
		if($kw)
		{
			if($tys==1)
			{
				$where.=" AND ( tb_kd like '%".$kw."%')";

			}elseif($tys==2)
			{
				$where.=" AND (orderstockid like '%".$kw."%' )";

			}elseif($tys==3)
			{
				$where.=" AND (tb_ordersn like '%".$kw."%' )";

			}else{
				$where.=" AND (tb_ordersn like '%".$kw."%' or tb_kd like '%".$kw."%' or orderstockid like '%".$kw."%')";
			}
			 $this->tpl->assign("kw", $kw);
		}
	
		$buyer = trim($this->input->get_post('buyer'));
		if($buyer){
			$where.=" AND createuser like '%".$buyer."%'";
			$this->tpl->assign("buyer", $buyer);
		}else{
			if($_COOKIE['department'] == 1 || $_COOKIE['classid']==10){ //超级管理员 1 仓管部门10
			}else{
				$where.=" AND createuser = '".$_COOKIE['username']."'";
			}
		}
		
		if($_COOKIE['ext_userid'])
		{
			$ext_userID = $_COOKIE['ext_userid'];
			$where.=" AND oper in ($ext_userID)";
			
		}else{
		
		}

		$buyerlist = $this->fun->getdatabaseslist('db_purchase_list'," AND createuser is NOT NULL ",'DISTINCT(createuser)');
		foreach($buyerlist as $key=>$rs)
		{
			$buyers[] = $rs['createuser'];
			$this->tpl->assign("buyerlist", $buyers);
		}


		$goodssku = trim($this->input->get_post('goodssku'));
		if($goodssku)
		{
			 $where.=" AND id in (SELECT pid FROM db_purchase_vice WHERE good_no like '%".$goodssku."%')";
			 $this->tpl->assign("goodssku", $goodssku);
		}
		$skucode = trim($this->input->get_post('skucode'));
		if($skucode)
		{
			 $where.=" AND id in (SELECT pid FROM db_purchase_vice WHERE skucode like '%".$skucode."%')";
			 $this->tpl->assign("skucode", $skucode);
		}
		$supplier = trim($this->input->get_post('supplier'));
		if($supplier){
			$where.=" AND made_factory = '{$supplier}' ";
			$this->tpl->assign('supplier',$supplier);
		}

		if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
            if (strstr($other, ",")) {
                $others = explode(",", $other);
                $where .= " and (";
                foreach ($others as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k A.orderId LIKE  " . $r." or `dealid` LIKE  '%" . $r."%' or `backdealid` LIKE  '%" . $r."%'" ;
                }
                $where .= ")";

            } else {
                $where .= " and  (
					 A.orderId LIKE  '" . $other . "'
					 or `dealid` LIKE '%".$other."%'
					 or `customerId` LIKE '%".$other."%'
					 or `backdealid`LIKE '%".$other."%'
					 or `mabangorderid`='".$other."'
					) ";
            }
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }


		$factorys = $this->fun->getdatabaseslist("db_factory");
		$this->tpl->assign("factorys",$factorys);
	

		$orderby = " order by id DESC";
		if($this->input->get('if_csv'))
		{
			$if_csv = 1;
		}
        $list = $this->fun->getalllist("db_purchase_list ", $where, $nowpage, $if_csv, $this->pageSize, $orderby);
		foreach($list["list"] as $key=>$rs)
		{
			 $waittime = strtotime($rs['opertime']) + 86400*$rs['daysum'];
			 $list["list"][$key]['waittime'] =date("Y-m-d H:i:s",$waittime);

			 $sql = "SELECT GROUP_CONCAT(good_no) as goods_no FROM db_purchase_vice WHERE pid = '{$rs['id']}' ";
			$res = $this->db->query($sql)->row_array();
			$list["list"][$key]['goods_no'] = str_replace(",","<br/>",$res['goods_no']);

			if($rs["id"] >386)
			{
				//10天变黄
				$times = strtotime($rs["opertime"])+86400*10;
				$twotimes = strtotime($rs["opertime"])+86400*20;
				if($times -time()<0 && time()<$twotimes )
				{
					$list["list"][$key]['colors'] = "#FF0"; 
				}

				if($twotimes -time()<0)
				{
					$list["list"][$key]['colors'] = "#F00"; 
				}

				$needtimes = strtotime($rs["opertime"])+86400*$rs["daysum"];
				if($needtimes - time() <0)
				{
					$list["list"][$key]['colors'] = "#F00"; 
				}
			}
		
			//20天变红
			//到期也变红

		}
		if($this->input->get('if_csv'))
		{
			$headers =array("订单编号","交易编号","商品编号","商品名称","客户姓名","客户国家(中)","客户国家(英)","店铺","工厂","平台","备注");
			foreach($list["list"] as $key=>$rs)
			{
			$listdata[$key][] = $rs["orderId"]; 
			$listdata[$key][] = $rs["backdealid"]; 
			$listdata[$key][] = $rs["goods_sku"]; 
			$listdata[$key][] = $rs["skuName"]; 
			$listdata[$key][] = $rs["customerName"]; 
			$listdata[$key][] = $rs["country"]; 
			$listdata[$key][] = $rs["engCountry"]; 
			$listdata[$key][] = $rs["shopId"]; 
			$listdata[$key][] = $rs["factoryl"]; 
			$listdata[$key][] = $rs["platformId"]; 
			$listdata[$key][] = $rs["descr"]; 
			}
			$this->fun->ouputexclePro($headers,$listdata);
		}
		 $factorylist=$this->db->get('db_factory')->result_array();
        $factory=array_column($factorylist,'name','id');
		$made_status=array("待生产","生产中","生产完成","已发运","已完成");
        $this->tpl->assign('made_status',$made_status);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("factory", $factory);
        $this->tpl->assign("orderlist", $list["list"]);
		
	
	
        $this->tpl->display("purchase/purchaselist.tpl");
	}
	
	function ajaxbutton()
	{
		$op = $this->input->get_post('op');

		//更新相关备注信息，若为工厂批量订单，则同时更新相关备注信息
		if($op=='updMemoData'){
			$id = $this->input->post('vice_id');
			$insttime = trim($this->input->post('insttime'));
			$goods_num = trim($this->input->post('goods_num'));
			$remarks = trim($this->input->post('remarks'));

			//先判断是否为工厂订单
			$fields = "a.goods_id,a.good_no,a.good_name,a.nums,a.qualityinNum,a.price,b.tb_ordersn,c.goods_parent_sku,b.cang,a.id,b.id as order_id,b.made_factory,b.id as purchase_id ";
			$sql = "SELECT $fields FROM db_purchase_vice a LEFT JOIN db_purchase_list b ON a.pid = b.id ";
			$sql.= "LEFT JOIN db_goods c ON a.goods_id = c.goods_id ";
			$sql.= "WHERE a.id = {$id} ";
			$sql.= "ORDER BY a.id DESC ";
			$rs  = $this->db->query($sql)->row_array();

			$this->db->trans_begin();

			//质检入库时，同时填写质检入库数量 2018/2/24
			$sql_vice_log = "SELECT sum(inStockNum) as inStockNum FROM db_purchase_vicelog WHERE pid = '{$id}' ";
			$rs_vice_log  = $this->db->query($sql_vice_log)->row_array();
			if($rs_vice_log){
				$vice_num = $rs_vice_log['inStockNum'];
			}else{
				$vice_num = 0;
			}
			$quality_num = $goods_num + $vice_num;
			//$quality_num = $goods_num + $rs['qualityinNum'];
			$this->db->update("db_purchase_vice",array("qualityinNum"=>$quality_num)," id = '".$id."'");


			//更新备注信息
			$vicelog = array();
			$vicelog['goods_id'] = $rs['goods_id'];
			$vicelog['good_no'] = $rs['good_no'];
			$vicelog['good_name'] = $rs['good_name'];
			$vicelog['good_parent_sku'] = $rs['goods_parent_sku'];
			$vicelog['inStockNum'] = $goods_num;
			$vicelog['insttime'] = $insttime;
			$vicelog['memo'] = $remarks;
			$vicelog['pid'] = $id;
			$vicelog['userid'] = $_COOKIE['userid'];
			$vicelog['username'] = $_COOKIE['username'];
			$vicelog['createtime'] = date("Y-m-d H:i:s");
			$vicelog['cang'] = $rs['cang'];
			$this->db->insert('db_purchase_vicelog',$vicelog);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
			$insert_id = $this->db->insert_id();


			//保存库存
			if($rs['cang']==2){
				$storage_id = 2;
				$storage_name = "二号仓";
			}else{
				$storage_id = 1; 
				$storage_name = "一号仓";
			}
			$sql_stock = "SELECT * FROM db_goods_stock WHERE goods_id = '{$rs['goods_id']}' AND storage_id = {$storage_id} "; //默认入库一号仓
			$rs_stock  = $this->db->query($sql_stock)->row_array();
			if($rs_stock['stock']<0){
				$rs_stock['stock'] = 0;
			}

			$cotnet = "手动入库";
			$instock = $goods_num;
			$this->fun->savestock($rs['goods_id'],$storage_name,$instock,0);
			//存日志
			$oldnum = $rs_stock['stock'];
			$newnum = $rs_stock['stock']+$goods_num;
			
			$this->fun->goods_stock_log($rs['order_id'],$rs['goods_id'],0,$cotnet,$instock,1,$oldnum,$newnum);    //库存日志

			//更新 db_goods_handstorage
			$post="";
			$detail = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".$rs['good_no']."'");
			if($detail)
			{
				$detailimg= $this->fun->getdatabasesdetail('db_goods_images'," AND goods_id='".$detail["goods_id"]."'");
				$post["goods_id"] = $detail['goods_id'];
				$post["goods_name"] = $detail['goods_name'];
				$post["oldnum"] = $oldnum;
				if(!$post["oldnum"]){
					$post["oldnum"] = 0;
				}
				$post["newnum"] = $oldnum+$goods_num;	//入库
				$post["images"] = $detailimg['thumb_url']?$detailimg['thumb_url']:"/fuman/images/s-l500.jpg";
				$post["goods_sku"] = $rs['good_no'];
				$post["goods_instock"] = $goods_num;
				$post["istype"] = 3; //质检入库
				$post["tostock"] = $rs['cang'];
				$post["status"] = 1;	//已处理状态
				$post["intime"] = time();
				$post["oper"] = $_COOKIE["userid"];
				$post["opername"] =  $_COOKIE["username"];
				$rsdbstock = $this->fun->getdatabasesdetail('db_storage'," AND id='".$rs['cang']."'");
				$post["storagename"] =  $rsdbstock["storagename"];
				$this->db->insert("db_goods_handstorage",$post);
			}
			//若该订单为批量订单，则同步备注信息 与 db_factory_scanorder表
			//工厂1或者工厂2 或者外部开发
			if($rs['made_factory']==1 || $rs['made_factory']==2 || $rs['made_factory']==7){
				
				$sql_factory = "SELECT a.id,a.memo,a.product_type,a.goods_sku,b.goods_name,b.price,a.batchorder_id,b.factory_id,b.goods_code FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE batchorder_id = '{$rs['tb_ordersn']}' AND goods_id = {$rs['goods_id']} ";
				$rs_factory = $this->db->query($sql_factory)->row_array(); //只有一条记录
					
				//db_factory_scanorder 一条日志一条信息
				$postst = "";
				$postst["order_id"] = $rs_factory['batchorder_id'];
				$postst["goods_sku"] = $rs_factory['goods_code'];
				$postst["goods_sub_sku"] = $rs_factory['goods_sku'];

				//更新的是主SKU的goods_id
				$sql_goods = "SELECT * FROM db_goods WHERE goods_sku = '{$rs_factory['goods_code']}' ";
				$rs_goods = $this->db->query($sql_goods)->row_array();
				if (count($rs_goods) > 0) {
					$postst["goods_id"] = $rs_goods["goods_id"];
				}
				$postst["skuName"] = $rs_factory["goods_name"];
				$postst["goods_num"] = $goods_num;
				$postst["price"] = $rs_factory["price"];
				$postst["specifications"] = $rs_factory['product_type'];

				if ($rs['made_factory'] == 1) {
					$factorylistname = "工厂1";
					$factoryID = 1;
					$postst["factoryID"] = $factoryID;
					$postst["factoryName"] = $factorylistname;
				}
				if ($rs['made_factory'] == 2) {
					$factorylistname = "工厂2";
					$factoryID = 2;
					$postst["factoryID"] = $factoryID;
					$postst["factoryName"] = $factorylistname;
				}
				if ($rs['made_factory'] == 7) {
					$factorylistname = "外部开发";
					$factoryID = 7;
					$postst["factoryID"] = $factoryID;
					$postst["factoryName"] = $factorylistname;
				}
				$postst["settlementtime"] = $insttime;
				$postst["insttime"] = $vicelog['createtime'];
				$postst["oper"] = $_COOKIE["username"];
				$postst["type"] = 2;
				$postst['memo'] = $remarks;
				$this->db->insert("db_factory_scanorder", $postst);
				$scan_id = $this->db->insert_id();
				$this->db->update("db_purchase_vicelog",array("scan_id"=>$scan_id)," id = '".$insert_id."'");


				if($rs['purchase_id']>500) {
				
					if (count($rs_factory) > 0) {
						if ($rs_factory['memo']) {
							$memo = $rs_factory['memo'] . $remarks . "<br/>";
						} else {
							$memo = $remarks . "<br/>";
						}
						//批量订单列表
						$this->db->update("db_batchorder_list", array('memo' => $memo), " id = " . $rs_factory['id']);
						//插入日志记录
						$message = "商品编号：{$rs_factory['goods_code']},型号：{$rs_factory["product_type"]}," . " 备注新增内容：{$remarks}";
						$arr_log = array();
						$arr_log['createtime'] = $vicelog['createtime'];
						$arr_log['goods_code'] = $rs_factory['goods_code'];
						$arr_log['order_id'] = $rs_factory['batchorder_id'];
						$arr_log['details'] = $message;
						$arr_log['userid'] = $_COOKIE['userid'];
						$arr_log['username'] = $_COOKIE['username'];
						$this->db->insert('db_batchorder_log', $arr_log);

						
						
					}
				}
			}
			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
			}
			else
			{
				$this->db->trans_commit();
			}

			if($insert_id){
				echo 200;exit;
			}else{
				echo 201;exit;
			}

		}
		//删除db_purchase_vicelog备注信息
		if($op=="delMemo"){

			$this->db->trans_begin();
			$id   = trim($this->input->post("id"));
			$sql = "SELECT * FROM db_purchase_vicelog WHERE id = '{$id}' ";
			$rs  = $this->db->query($sql)->row_array();
			//更新库存
			$stockNum = $rs['inStockNum'];
			//保存库存
			if($rs['cang']==2){
				$storage_id = 2;
				$storage_name = "二号仓";
			}else{
				$storage_id = 1;
				$storage_name = "一号仓";
			}
			$sql_stock = "SELECT * FROM db_goods_stock WHERE goods_id = '{$rs['goods_id']}' AND storage_id = {$storage_id} "; //默认入库一号仓
			$rs_stock  = $this->db->query($sql_stock)->row_array();
			$cotnet = "手动出库";
			$instock = -$rs['inStockNum'];
			$this->fun->savestock($rs['goods_id'],$storage_name,$instock,0);
			//存日志
			$oldnum = $rs_stock['stock'];
			$newnum = $rs_stock['stock']-$rs['inStockNum'];
			$this->fun->goods_stock_log($rs['id'],$rs['goods_id'],0,$cotnet,$instock,0,$oldnum,$newnum);    //库存日志

			//质检出库
			$post="";
			$detail = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".$rs['good_no']."'");
			if($detail)
			{
				$detailstock = $this->fun->getdatabasesdetail('db_goods_stock'," AND goods_id='".$detail["goods_id"]."' AND storage_id = '".$rs['cang']."' ");
				$detailimg= $this->fun->getdatabasesdetail('db_goods_images'," AND goods_id='".$detail["goods_id"]."'");
				$oldnum = $detailstock['stock']?$detailstock['stock']:0;
				$post["goods_id"] = $detail['goods_id'];
				$post["goods_name"] = $detail['goods_name'];
				$post["oldnum"] = $oldnum+$rs['inStockNum']; //上面库存已经减掉了
				$post["newnum"] = $oldnum;	//新库存数量
				if($post['newnum']<0){
					$post['newnum'] =0;
				}
				$post["images"] = $detailimg['thumb_url']?$detailimg['thumb_url']:"/fuman/images/s-l500.jpg";
				$post["goods_sku"] = $rs['good_no'];
				$post["goods_instock"] = -$rs['inStockNum'];
				$post["istype"] = 4; //质检出库
				$post["tostock"] = $rs['cang'];
				$post["status"] = 1;	//已处理状态
				$post["intime"] = time();
				$post["oper"] = $_COOKIE["userid"];
				$post["opername"] =  $_COOKIE["username"];
				$rsdbstock = $this->fun->getdatabasesdetail('db_storage'," AND id='".$rs['cang']."'");
				$post["storagename"] =  $rsdbstock["storagename"];
				$this->db->insert("db_goods_handstorage",$post);
			}

			//若该订单为批量订单，则删除相关信息
			$fields = "a.goods_id,a.good_no,a.good_name,a.nums,a.qualityinNum,a.price,b.tb_ordersn,c.goods_parent_sku,b.cang,a.id,b.id as order_id,b.made_factory,b.id as purchase_id ";
			$sqls = "SELECT $fields FROM db_purchase_vice a LEFT JOIN db_purchase_list b ON a.pid = b.id ";
			$sqls.= "LEFT JOIN db_goods c ON a.goods_id = c.goods_id ";
			$sqls.= "WHERE a.id = {$rs['pid']} ";
			$sqls.= "ORDER BY a.id DESC ";
			$res  = $this->db->query($sqls)->row_array();

			//工厂1或者工厂2
			if($res['made_factory']==1 || $res['made_factory']==2 || $res['made_factory']==7){
				if($res['purchase_id']>500) {
					$sql_factory = "SELECT a.id,a.memo,a.product_type,a.goods_sku,b.goods_name,a.price,a.batchorder_id,b.factory_id,b.goods_code FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE batchorder_id = '{$res['tb_ordersn']}' AND goods_id = {$res['goods_id']} ";
					$rs_factory = $this->db->query($sql_factory)->row_array(); //只有一条记录
					//工厂批量订单，备注信息删除
					if (count($rs_factory) > 0) {
						$content = $rs['memo'] . "<br/>";
						$db_content = $rs_factory['memo'];
						$memo = str_replace($content, "", $db_content);  //更新备注信息
						//批量订单列表
						$this->db->update("db_batchorder_list", array('memo' => $memo), " id = " . $rs_factory['id']);

						//db_factory_scanorder 一条日志删除  这里有bug
						//$arr_condition = array();
						//$arr_condition['goods_sub_sku'] = $rs['good_no'];
						//$arr_condition['memo'] = $rs['memo'];
						//$arr_condition['goods_num'] = $rs['inStockNum'];
						//$arr_condition['order_id'] = $rs_factory['batchorder_id'];
						$this->db->delete("db_factory_scanorder", array("id"=>$rs['scan_id']));
					}
				}else{
					if($rs['scan_id']){
						$this->db->delete("db_factory_scanorder", array("id"=>$rs['scan_id']));
					}

				}

			}


			//删除质检入库时，同时扣减质检入库数量 2018/2/24
			$quality_num =  $res['qualityinNum']-$stockNum;
			if($quality_num<0){
				$quality_num = 0;
			}
			$this->db->update("db_purchase_vice",array("qualityinNum"=>$quality_num)," id = '".$rs['pid']."'");


			$this->db->delete('db_purchase_vicelog'," id = ".$id);




			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
			}
			else
			{
				$this->db->trans_commit();
			}
			echo 200;exit;
			/**
			if($this->db->affected_rows()){
				echo 200;exit;
			}else{
				echo 202;exit;
			}**/
		}
		if($op =='getStockSInfo')
		{
			 echo json_encode($this->m->getStockSInfo(trim($this->input->post('val'))));
		}
		if($op == "saveslistget")
        {
			$res = $this ->m->saveslistget($_REQUEST["id"],$_REQUEST["st"]);
			echo json_encode($res);
			die;
        }
		if($op =='batchPaystatus')
		{
			$id = $this->input->post('id');
			if($id)
			{
				$id = trim($id,",");
				$this->db->update("db_purchase_list",array('ps'=>2)," id in($id) AND ps = 1");
			}
			echo json_encode($id);
			die;
		}
		if($op == "changeStorage")
		{
			//更改库存时，同时需要修改在途数
			$id = trim($this->input->post("id"));
			$storage_id = trim($this->input->post("storageid"));
			$this->db->update("db_purchase_list",array('cang'=>$storage_id)," id = '".$id."'");
			//在途数量修改 代码定期执行 这里不做判断
			//$sql_purchase_list = "SELECT * FROM db_purchase_list ";

			if($this->db->affect_rows()){
				echo 200;exit;
			}else{
				echo 201;exit;
			}

		}
		if($op =='saverightadd')
		{
			$id = $this->input->post('id');
			$idc = $this->input->post('idc');
			$Nums = $this->input->post('Nums');
			$storagecang = trim($this->input->post("storagecang"));
			if($idc && $Nums)
			{
			  $barcode = substr($idc, 0, -1);
			  $barid = explode(",", $barcode);

			  $Nums = substr($Nums, 0, -1);
			  $qNums = explode(",", $Nums);

			  //判断是否全部未质检，若全部未质检，则质检完成,并入库相关数据
			  //若存在已经质检的相关商品，则不做入库的相关操作
			  $check_flag = 0;
			  for($j=0;$j<count($barid);$j++){
				  //检索并执行相关操作
				  $sql_vice_log = "SELECT * FROM db_purchase_vicelog WHERE pid = '{$barid[$j]}' ";
				  $rs_vice_log  = $this->db->query($sql_vice_log)->row_array();
				  if(count($rs_vice_log)>0){
					  $check_flag = 1;
					  break;
				  }
			  }

				$this->db->trans_begin(); //事物开始


			  if($check_flag==1){ //说明存在已质检的商品，默认全部质检过
				  $batch_flag = 0;
				  //$purchase_id = 0;
				  $sql_p = "SELECT b.id as purchase_id,b.tb_ordersn,b.made_factory FROM db_purchase_vice a LEFT JOIN db_purchase_list b ON a.pid = b.id WHERE a.id = {$barid[0]} ";
				  $rs_p  = $this->db->query($sql_p)->row_array();
				  $purchase_id = $rs_p['purchase_id'];

				  //全部质检通过是，若为批量订单，则更新状态
				  if($rs_p['made_factory']==1 ||$rs_p['made_factory']==2 ){
					  $s_batch = "SELECT * FROM db_batchorder WHERE order_id = '{$rs_p['tb_ordersn']}' ";
					  $r_batch = $this->db->query($s_batch)->row_array();
					  if(count($r_batch)>0){
						  if($r_batch['status']==7){
						  }else{
							  //更新批量订单为公司验收完成状态
							  $this->db->update('db_batchorder', array('status' => 7), " order_id = '" . $rs_p['tb_ordersn'] . "'");
						  }
					  }
				  }



			  }else{
				//所有商品 一起进行入库
				  $batch_flag = 1;
				  $purchase_id = 0;
				  for($c=0;$c<count($barid);$c++){

					  //先判断是否为工厂订单
					  $fields = "a.goods_id,a.good_no,a.good_name,a.price,a.nums,b.tb_ordersn,c.goods_parent_sku,b.cang,a.id,b.id as order_id,b.made_factory,b.id as purchase_id ";
					  $sql = "SELECT $fields FROM db_purchase_vice a LEFT JOIN db_purchase_list b ON a.pid = b.id ";
					  $sql.= "LEFT JOIN db_goods c ON a.goods_id = c.goods_id ";
					  $sql.= "WHERE a.id = {$barid[$c]} ";
					  $sql.= "ORDER BY a.id DESC ";
					  $rs  = $this->db->query($sql)->row_array();
					  $purchase_id = $rs['purchase_id'];
					  if($rs['made_factory']==1 ||$rs['made_factory']==2 ){
						  $s_batch = "SELECT * FROM db_batchorder WHERE order_id = '{$rs['tb_ordersn']}' ";
						  $r_batch = $this->db->query($s_batch)->row_array();
						  if(count($r_batch)>0){
							  if($r_batch['status']==7){
							  }else{
								  //更新批量订单为公司验收完成状态
								  $this->db->update('db_batchorder', array('status' => 7), " order_id = '" . $rs['tb_ordersn'] . "'");
							  }
						  }
					  }

					  //更新备注信息
					  $vicelog = array();
					  $vicelog['goods_id'] = $rs['goods_id'];
					  $vicelog['good_no'] = $rs['good_no'];
					  $vicelog['good_name'] = $rs['good_name'];
					  $vicelog['good_parent_sku'] = $rs['goods_parent_sku'];
					  $vicelog['inStockNum'] = $rs['nums'];
					  $vicelog['insttime'] = date("Y-m-d");
					  $vicelog['memo'] = "(".date("Y-m-d").",".$rs['nums'].")";
					  $vicelog['pid'] = $barid[$c];
					  $vicelog['userid'] = $_COOKIE['userid'];
					  $vicelog['username'] = $_COOKIE['username'];
					  $vicelog['createtime'] = date("Y-m-d H:i:s");
					  $vicelog['cang'] = $rs['cang'];
					  $this->db->insert('db_purchase_vicelog',$vicelog);
					  $insert_id = $this->db->insert_id();

					  //质检入库时，同时填写质检入库数量 2018/2/24
					  $this->db->update("db_purchase_vice",array("qualityinNum"=>$rs['nums'])," id = '".$barid[$c]."'");



					  //保存库存
					  if($rs['cang']==2){
						  $storage_id = 2;
						  $storage_name = "二号仓";
					  }else{
						  $storage_id = 1;
						  $storage_name = "一号仓";
					  }
					  $sql_stock = "SELECT * FROM db_goods_stock WHERE goods_id = '{$rs['goods_id']}' AND storage_id = {$storage_id} "; //默认入库一号仓
					  $rs_stock  = $this->db->query($sql_stock)->row_array();
					  if($rs_stock['stock']<0){
						  $rs_stock['stock'] = 0;
					  }

					  $cotnet = "手动入库";
					  $instock = $rs['nums'];
					  $this->fun->savestock($rs['goods_id'],$storage_name,$instock,0);
					  //存日志
					  $oldnum = $rs_stock['stock'];
					  $newnum = $rs_stock['stock']+$rs['nums'];
					  $this->fun->goods_stock_log($rs['order_id'],$rs['goods_id'],0,$cotnet,$instock,1,$oldnum,$newnum);    //库存日志

					  //更新 db_goods_handstorage
					  $post="";
					  $detail = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".$rs['good_no']."'");
					  if($detail)
					  {
						  $detailstock = $this->fun->getdatabasesdetail('db_goods_stock'," AND goods_id='".$detail["goods_id"]."' AND storage_id = '".$rs['cang']."' ");
						  $detailimg= $this->fun->getdatabasesdetail('db_goods_images'," AND goods_id='".$detail["goods_id"]."'");
						  $oldnum = $detailstock['stock']?$detailstock['stock']:0;
						  $post["goods_id"] = $detail['goods_id'];
						  $post["goods_name"] = $detail['goods_name'];
						  $post["oldnum"] = $oldnum;
						  $post["newnum"] = $oldnum+$rs['nums'];	//入库
						  $post["images"] = $detailimg['thumb_url']?$detailimg['thumb_url']:"/fuman/images/s-l500.jpg";
						  $post["goods_sku"] = $rs['good_no'];
						  $post["goods_instock"] = $rs['nums'];
						  $post["istype"] = 3; //质检入库
						  $post["tostock"] = $rs['cang'];
						  $post["status"] = 1;	//已处理状态
						  $post["intime"] = time();
						  $post["oper"] = $_COOKIE["userid"];
						  $post["opername"] =  $_COOKIE["username"];
						  $rsdbstock = $this->fun->getdatabasesdetail('db_storage'," AND id='".$rs['cang']."'");
						  $post["storagename"] =  $rsdbstock["storagename"];
						  $this->db->insert("db_goods_handstorage",$post);
					  }
				  } //end for
			  }

				//若直接点击全部质检完成的时候才执行该段代码
			if($batch_flag==1 || $purchase_id<=500){  //$purchase_id<=500 流程变更，过渡阶段代码
				 for($i=0;$i<count($barid);$i++)
				 {
					 /**
					 if($purchase_id==0){ //不用执行，直接退出循环
						 break;
					 }**/
					$sql = "UPDATE db_purchase_vice SET qualityinNum='".$qNums[$i]."' WHERE  id='".$barid[$i]."' ";
					$this->db->query($sql);

					 //判断批量订单 更新备注
					 $fields = "a.goods_id,a.good_name,a.cang,a.good_parent_sku,a.memo,a.createtime,a.userid,a.username,c.made_factory,c.id as purchase_id ";
					 $fields.= ",a.insttime,a.good_no,a.inStockNum";
					 $fields.= ",c.tb_ordersn,b.price ";
					 $sql_vicelog = "SELECT $fields FROM db_purchase_vicelog a ";
					 $sql_vicelog.= "LEFT JOIN db_purchase_vice b ON b.id = a.pid ";
					 $sql_vicelog.= "LEFT JOIN db_purchase_list c ON c.id = b.pid ";
					 $sql_vicelog.= "WHERE a.pid = {$barid[$i]} ";
					 $rs_vicelog  = $this->db->query($sql_vicelog)->result_array();
					 if(count($rs_vicelog)>0){
						 foreach($rs_vicelog as $k=>$v) {
							 $factory_flag = substr($v['good_parent_sku'], 0, 2);
							 if($v['made_factory']==1 || $v['made_factory']==2){
								 if (strlen($v['good_parent_sku']) == 8) {
									 if ($factory_flag == "11" || $factory_flag == "12") { //工厂订单 额外处理
										 $sql_factory = "SELECT a.id,a.memo,a.product_type,a.batchorder_id,b.factory_id FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE batchorder_id = {$v['tb_ordersn']} AND goods_id = {$v['goods_id']} ";
										 $rs_factory = $this->db->query($sql_factory)->row_array(); //只有一条记录
										 if (count($rs_factory) > 0) {
											 if ($rs_factory['memo']) {
												 $memo = $rs_factory['memo'] . $v['memo'] . "<br/>";
											 } else {
												 $memo = $v['memo'] . "<br/>";
											 }
											 //批量订单列表
											 $this->db->update("db_batchorder_list", array('memo' => $memo), " id = " . $rs_factory['id']);
											 //插入日志记录
											 $message = "商品编号：{$v['good_parent_sku']},型号：{$rs_factory["product_type"]}," . " 备注新增内容：{$v['memo']}";
											 $arr_log = array();
											 $arr_log['createtime'] = $v['createtime'];
											 $arr_log['goods_code'] = $v['good_parent_sku'];
											 $arr_log['order_id'] = $rs_factory['batchorder_id'];
											 $arr_log['details'] = $message;
											 $arr_log['userid'] = $v['userid'];
											 $arr_log['username'] = $v['username'];
											 //$arr_log['cang'] = $storagecang;
											 $this->db->insert('db_batchorder_log', $arr_log);
											 //更新批量订单为打款状态
											 $this->db->update('db_batchorder', array('status' => 7), " order_id = '" . $rs_factory['batchorder_id'] . "'");


											 //db_factory_scanorder 一条日志一条信息
											 $postst = "";
											 $postst["order_id"] = $rs_factory['batchorder_id'];
											 $postst["goods_sku"] = $v['good_parent_sku'];
											 $postst["goods_sub_sku"] = $v['good_no'];

											 //更新的是主SKU的goods_id
											 $sql_goods = "SELECT * FROM db_goods WHERE goods_sku = '{$v['good_parent_sku']}' ";
											 $rs_goods = $this->db->query($sql_goods)->row_array();
											 if (count($rs_goods) > 0) {
												 $postst["goods_id"] = $rs_goods["goods_id"];
											 }
											 $postst["skuName"] = $v["good_name"];
											 $postst["goods_num"] = $v['inStockNum'];
											 $postst["price"] = $v["price"];
											 $postst["specifications"] = $rs_factory['product_type'];

											 if ($rs_factory['factory_id'] == 1) {
												 $factorylistname = "工厂1";
												 $factoryID = 1;
												 $postst["factoryID"] = $factoryID;
												 $postst["factoryName"] = $factorylistname;
											 }
											 if ($rs_factory['factory_id'] == 2) {
												 $factorylistname = "工厂2";
												 $factoryID = 2;
												 $postst["factoryID"] = $factoryID;
												 $postst["factoryName"] = $factorylistname;
											 }
											 $postst["settlementtime"] = $v['insttime'];
											 $postst["insttime"] = $v['createtime'];
											 $postst["oper"] = $v["username"];
											 $postst["type"] = 2;
											 $postst['memo'] = $v['memo'];
											 $this->db->insert("db_factory_scanorder", $postst);


										 }
									 }
								 }
						 }//made_factory if判断

						 } //vicelog 循环结束
					 }//vicelog end



				 } //for end
			} //$batch_flag end

			 $post="";
			 $post['chkflag'] = 1;
			 $post['chktimes'] = date("Y-m-d H:i:s");
			 $post['chkmemberlist'] = $_COOKIE['username'];
			 $this->db->update('db_purchase_list',$post,'id='.$id);
			 $this->m->upstatus_list($id,25,'质检完成');

			 //质检完成的时候，将标识码清空
			 $this->db->query("update db_purchase_vice set skumemo = CONCAT(skumemo,'->',skucode) where pid = '".$id."'");
			 $this->db->query("update db_purchase_vice set skucode = '' where pid = '".$id."'");

			 //添加日志信息
			$msg = "状态由：采购完成,更改为：质检完成";
			$arr_logs['createtime'] = date("Y-m-d H:i:s");
			$arr_logs['goods_code'] = $id;
			$arr_logs['details'] = $msg;
			$arr_logs['username'] = $_COOKIE['username'];
			$arr_logs['userid'] = $_COOKIE['userid'];
			$arr_logs['purchase_id'] = $id;
			$this->db->insert('db_externalbuy_log', $arr_logs);

				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
				}

				 echo 200;exit;
			}else{
				echo 201;
				exit;
			}
			
		}
		if($op =='barcode')
		{
			$idc = $this->input->get('idc');
			$cang = $this->input->get('cang');
			 $barcode = substr($idc, 0, -1);
			 $barid = explode(",", $barcode);
			 for($i=0;$i<count($barid);$i++)
			 {
				$sql = "SELECT nums,good_name,good_no,goods_id FROM db_purchase_vice WHERE  id='".$barid[$i]."' ";
				$res = $this->db->get_one($sql);

				$respositions = $this->db->get_one("select * from db_goods_stock where goods_id='".$res['goods_id']."' AND storage_id='".$cang."'");
				$num[] = $res['nums'];
				$goods_name[] = $res["good_name"];
				$positions[] = $respositions["positions"];
				$goods_sku[] = $res["good_no"];
			 }
			if($goods_sku)
			{
				$str="";
				foreach($goods_sku as $key=>$rs)
				{
					$st = $key+1;
					for($i=1;$i<=$num[$key];$i++)
					{
						$st = $num[$key];
						$mum = $i."/".$st;
						$str.='<div style=" width:75mm; height:20mm; margin-left:2.5mm;page-break-after:always;"><ul style="width:70mm; height:8mm; margin-left:2.5mm;"><li>';
						$str.=" <img src=\"/fuman/barcode/html/image.php?filetype=PNG&dpi=72&scale=1&rotation=0&font_family=0&font_size=8&text={$rs}&thickness=30&checksum=&code=BCGcode39\" style=\" height:7mm; width:300px;\"> </li></ul>";
						$str.=' <ul style="width:70mm; height:2mm; margin-left:2.5mm;"> <li style="text-align:center; font-size:13px; font-weight:bold; width:44mm; overflow:hidden;white-space:nowrap; text-overflow:ellipsis;">';
						$str.=$goods_sku[$key];
						$str.=' </li><li style="text-align:center; font-size:12px;width:25mm;">'.$positions[$key];
						$str.="</li></ul>";
						$str.='<ul style="width:70mm; height:2mm;"><li style=" width:34mm; float:left; font-size:12px; text-align:left;">'.$goods_name[$key].date("m-d");
						$str.='</li><li style=" width:34mm; float:left; font-size:12px; text-align:right;">'.$mum.' </li></ul>';
						$str.='<ul style="width:70mm; height:2mm;"><li style=" width:34mm; font-size:24px; text-align:center;">MADE IN CHINA</li></ul>';
						$str.='</div>';
					}
				}
				$this->tpl->assign("str", $str);
			$this->tpl->display("product/printcode.tpl",0,0,1);
		
			}
		}
		if($op =='delstocklist')
		{
			$id = trim($this->input->post('id'));
			$sql = "SELECT * FROM db_purchase_list WHERE id = '{$id}' ";
			$rs  = $this->db->query($sql)->row_array();
			if($rs['made_factory']==1 || $rs['made_factory']==2){
				$sql_batchorder = "SELECT * FROM db_batchorder WHERE order_id = '{$rs['tb_ordersn']}' ";
				$rs_batchorder  = $this->db->query($sql_batchorder)->row_array();
				if(count($rs_batchorder)>0){
					if($rs_batchorder['status']==4 || $rs_batchorder['status']==3){ //新订单或已作废
						$this->db->update('db_batchorder',array('status'=>3)," order_id = '".$rs['tb_ordersn']."'"); //作废该订单
					}else{
						echo 201;exit; //该状态批量订单不能删除
					}
					
				}
			}
			$this->db->delete('db_purchase_list',"id='".intval($this->input->post('id'))."'");
			$this->db->delete('db_purchase_status',"s_sid='".intval($this->input->post('id'))."'");
			$this->db->delete('db_purchase_vice',"pid='".intval($this->input->post('id'))."'");

		}
		if($op =='delstock')
		{
			$this->db->delete('db_goods_handstorage',"id='".intval($this->input->post('id'))."' AND status=0");
		}
		if($op =='confirk')
		{
			$id = intval($this->input->post('id'));
			$rsdb = $this->fun->getdatabasesdetail('db_goods_handstorage'," AND id='{$id}' AND status =0");
			
			if($rsdb["istype"]==1)
			{
				$cotnet = "手动入库";
				$instock = $rsdb['goods_instock'];
				$types = 1;
			}else{
				$cotnet = "手动出库";
				$instock = "-".$rsdb['goods_instock'];
				$types = 0;
			}
			$this->db->update("db_goods_handstorage",array("status"=>1),"id=".$id);
			$this->fun->savestock($rsdb['goods_id'],$rsdb['storagename'],$instock,0);
			//存日志
			$this->fun->goods_stock_log($rsdb['id'],$rsdb['goods_id'],0,$cotnet,$instock,$types,$rsdb["oldnum"],$rsdb["newnum"]);    //库存日志
		}
		if($op =='showsavebuy')
		{
			$id = $this->input->post('id');
			$detail = $this->fun->getdatabasesdetail('db_purchase_list'," AND id='{$id}'");
			//如果是厂1厂2广州直接完成
			
			if($detail['made_factory'] ==1 || $detail['made_factory'] ==2 || $detail['made_factory'] ==7)
			{
				$post="";
				$post['tb_kd'] = $detail["orderstockid"];
				$post['kdname'] = $detail["orderstockid"];
				$post['status'] = 2;
				$this->db->update('db_purchase_list',$post,"id='".$id."'");
				$this->m->upstatus_list($id,24,'采购完成');

				//添加日志信息
				$msg = "状态由：已支付,更改为：采购完成";
				$arr_logs['createtime'] = date("Y-m-d H:i:s");
				$arr_logs['goods_code'] = $detail['orderstockid'];
				$arr_logs['details'] = $msg;
				$arr_logs['username'] = $_COOKIE['username'];
				$arr_logs['userid'] = $_COOKIE['userid'];
				$arr_logs['purchase_id'] = $id;
				$this->db->insert('db_externalbuy_log', $arr_logs);
				$tb_ordersnst = 201;
				echo json_encode($tb_ordersnst);
				die;
			}else{
				if($detail['tb_ordersn']){
					$tb_ordersnst = explode("\r\n",$detail['tb_ordersn']);
				}
			}
			echo json_encode($tb_ordersnst);
			die;
		}
		if($op =='editsavebuy')
		{
			$id = $this->input->post('id');
			$detail = $this->fun->getdatabasesdetail('db_purchase_list'," AND id='{$id}'");
			if(strstr($detail["tb_kd"],"tborder"))
			{
				if($detail['tb_kd']){
					$tb_ordersnst = unserialize($detail['tb_kd']);
				}else{
					$tb_ordersnst = explode("\r\n",$detail['tb_ordersn']);
				}
				echo json_encode($tb_ordersnst);
				die;
			}else{
				$newarr=array();
				$newarr["tborder"] = $detail["tb_ordersn"];
				$newarr["kdname"] = $detail["kdname"];
				$newarr["kdnumber"] = $detail["tb_kd"];

				
				$tb_ordersnst = serialize($newarr);
				$tb_ordersnst = unserialize($tb_ordersnst);
				echo json_encode($tb_ordersnst);
				die;
			}
			
			
		}
		if($op =='editSave')
		{
			$orderid = $this->input->post('purchaselist_id');
			$newarray["tborder"] = $this->input->post('tborder');
			$newarray["kdname"] = $this->input->post('kdname');
			$newarray["kdnumber"] = $this->input->post('kdnumber');

			$newarr = serialize($newarray);
			$post="";
			$post['tb_kd'] = $newarr;
			
		
			$post="";
			$post['tb_kd'] = trim($this->input->post('kdnumber'));
			$post['kdname'] =trim($this->input->post('kdname'));
			$post['tb_ordersn'] = trim($this->input->post('tborder'));
			
			$this->db->update('db_purchase_list',$post,"id='".$orderid."'");
			header("location:/purchase/purchaselist?id={$orderid}");
		}

		if($op =='savekd')
		{
			$orderid = $this->input->post('orderid');
			$newarray["tborder"] = $this->input->post('tborder');
			$newarray["kdname"] = $this->input->post('kdname');
			$newarray["kdnumber"] = $this->input->post('kdnumber');

			$post="";
			$post['tb_kd'] = $newarray["kdnumber"][0];
			$post['kdname'] = $newarray["kdname"][0];
		
			$post['status'] = 2;
			$this->db->update('db_purchase_list',$post,"id='".$orderid."'");
			$this->m->upstatus_list($orderid,24,'采购完成');

			//添加日志信息
			$sql = "SELECT * FROM db_purchase_list WHERE id  = '{$orderid}' ";
			$detail  = $this->db->query($sql)->row_array();

			$msg = "状态由：已支付,更改为：采购完成";
			$arr_logs['createtime'] = date("Y-m-d H:i:s");
			//$arr_logs['pid'] = "";
			$arr_logs['goods_code'] = $detail['orderstockid'];
			$arr_logs['details'] = $msg;
			$arr_logs['username'] = $_COOKIE['username'];
			$arr_logs['userid'] = $_COOKIE['userid'];
			$arr_logs['purchase_id'] = $orderid;
			$this->db->insert('db_externalbuy_log', $arr_logs);


			header("location:/purchase/purchaselist?id={$orderid}");
		}

		if($op =='noscaninall')
		{
			$id = intval($this->input->post('id'));
			$rsdb = $this->db->get_where('db_purchase_vice',"pid='".$id."'")->result_array();
			if(count($rsdb)>0)
			{
				echo json_encode($rsdb);
				die;
			}
		}
		if($op =='savefullnewadd')
		{
			$id = intval($this->input->post('id'));
			$this->m->savefullnewadd($id);
			echo 200;
			die;
		}

		/*****盘点入库***/
		if($op =='savehandinputstock')
		{
			$skustr = $this->input->post('skustr');
			$tostock = $this->input->post('tostock');
			
			if($skustr=='')die(201);
			$newarray = array();
			$impstr = explode("\n",$skustr);
			if(count($impstr)>0)
			{
				foreach($impstr as $key=>$goods)
				{
					 $goodsstr = str_replace("，", ",", $goods); //替换英文逗号,
					 $goodsdb = explode(",",$goodsstr);
					 $goods_sku = $goodsdb[0];
					 $goods_num = $goodsdb[1];
					
					 $detail = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".$goods_sku."'");
					 if(!$detail)
					{
						echo json_encode(array("code"=>202,"txt"=>"{$goods_sku}不存在，盘点失败"));
						die;
					 }else{
						$newarray[$key]["goods_id"] = $detail['goods_id'];
						$newarray[$key]["goods_sku"] = $detail['goods_sku'];
						$newarray[$key]["goods_name"] = $detail['goods_name'];

						$detailstock = $this->fun->getdatabasesdetail('db_goods_stock'," AND goods_id='".$detail["goods_id"]."' AND storage_id = '".$tostock."' ");
						$newarray[$key]["goods_stock"] = $detailstock['stock'];
						$newarray[$key]["instock"] = $goods_num;
						$newarray[$key]["tostock"] = $tostock;
					 }

				 	
				}
			}
			echo json_encode($newarray);
			die;
			
		}
		if($op =='saveinputstockto')
		{
			
			
			$goods_id  =$this->input->post('goods_id');
			$instock  =$this->input->post('instock');
			$memo  =$this->input->post('memo');
			$tocang  =$this->input->post('tocang');

			if(count($goods_id)>0)
			{
				foreach($goods_id as $key=>$rs)
				{
					$this->db->trans_begin();
					$detail = $this->fun->getdatabasesdetail('db_goods'," AND goods_id='".$rs."'");
					
					$rsdbstock = $this->fun->getdatabasesdetail('db_storage'," AND id='".$tocang[$key]."'");
					$storagename =  $rsdbstock["storagename"];
	
					$rsdb = $this->fun->getdatabasesdetail('db_goods_stock'," AND goods_id='".$rs."' AND storage_id='".$tocang[$key]."'");
					$sql = "UPDATE db_goods_stock set stock='".$instock[$key]."' where id='".$rsdb["id"]."'";
					$this->db->query($sql);
					$this->fun->goods_update_log($rs,'盘点更新'.$storagename.'库存 ['.$instock[$key].'] 原库存 ['.$rsdb['stock'].']',1,$rsdb["stock"],$instock[$key]);	//更新了库存
					$this->fun->goods_stock_log($rs,$rs,0,'库存盘点',$instock[$key],1,$rsdb["stock"],$instock[$key]);    //存日志
					$post="";
					$post['goods_id'] = $rs;
					$post['goods_name'] = $detail['goods_name'];
					$post['oldnum'] = $rsdb["stock"];
					$post['newnum'] = $instock[$key];
					$post['goods_sku'] = $detail['goods_sku'];
					$post['goods_instock'] = $instock[$key];
					$post['tostock'] = $tocang[$key];
					$post['storagename'] = $storagename;
					$post['intime'] = time();
					$post['oper'] = $_COOKIE["userid"];
					$post['opername'] = $_COOKIE["username"];
					$post['memo'] = $memo[$key];
					$this->db->insert('db_goods_inventory',$post);
					if ($this->db->trans_status() === FALSE) {
						$this->db->trans_rollback();
					} else {
						$this->db->trans_commit();
					}
				}
			}
			
			header("location:/purchase/inputstock");
		}
	}
}
